package com.mycontract.suitepro.contract

import android.annotation.SuppressLint
import android.content.ClipboardManager
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.mycontract.suitepro.ProjectConfig
import com.mycontract.suitepro.R
import com.mycontract.suitepro.base.BaseActivity
import com.mycontract.suitepro.components.dialog.PermissionItem
import com.mycontract.suitepro.components.dialog.PermissionsDialog
import com.mycontract.suitepro.data.ReqBase
import com.mycontract.suitepro.databinding.ActivityContractSuiteLaunchBinding
import com.mycontract.suitepro.enums.PageTagEnum
import com.mycontract.suitepro.extend.*


/** 启动页 */
@SuppressLint("CustomSplashScreen")
class LaunchActivity : BaseActivity() {

    //布局binding
    private lateinit var mContractSuiteActivityContractSuiteBinding: ActivityContractSuiteLaunchBinding

    //权限弹框
    private val mPermissionsDialog = PermissionsDialog()

    // 主线程句柄
    private val mHandler: Handler = Handler(Looper.getMainLooper())

    // 主线程句柄
    private val mClipboardHandler: Handler = Handler(Looper.getMainLooper())

    //用户流程viewModel
    private val mContractViewModel by lazy {
        ViewModelProvider(this)[ContractViewModel::class.java]
    }

    override fun onContractSuiteBindingContractSuiteViewContractSuiteModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mContractViewModel)
        return list
    }

    override fun onContractSuiteBindingContractSuiteViewContractSuiteTag(): String {
        return PageTagEnum.launch.name.uppercase()
    }

    override fun onContractSuiteBindingContractSuiteContentContractSuiteView(): View {
        mContractSuiteActivityContractSuiteBinding =
            ActivityContractSuiteLaunchBinding.inflate(layoutInflater)
        return mContractSuiteActivityContractSuiteBinding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onContractSuiteContentContractSuiteViewContractSuiteBinded() {
        try {
            println("1==================")
            // 初始化模块
            val data: Uri? = intent.data
            ContractParamsFromApp.initSourceData(data)

            // 初始化权限弹框
            initPermissionDialogUI()

            // 获取app配置回调
            mContractViewModel.onGetAppConfigLiveData.observe(this) {
                if (it.isSuccess) {
                    val result = it.getOrNull()
                    if (result != null) {
                        if (result.showPer.equals("YES", true)) {
                            // 检查权限
                            checkPermissions()
                        } else {
                            // 去首页
                            toContractIndexPage()
                        }
                    } else {
                        // 去首页
                        toContractIndexPage()
                    }
                } else {
                    // 去首页
                    toContractIndexPage()
                }
            }

            // 初始化版本信息
            mContractSuiteActivityContractSuiteBinding.textLaunchProductVersion.text = getString(
                R.string.contract_suite_version_flag,
                "${ProjectConfig.CONTRACTSUITE_Version_NAME}(${ProjectConfig.CONTRACTSUITE_Version})"
            )

            // 获取手机前缀
            getAppConfig()

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()

        // 获取剪贴板内容
        getClipboardText()
    }

    override fun onDestroy() {
        mHandler.removeCallbacksAndMessages(null)
        mClipboardHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

    override fun onContractSuitePermissionsContractSuiteRequestContractSuiteAllContractSuitePass() {
        checkContractSuiteNextContractSuiteStepContractSuiteFromContractSuiteAllContractSuitePermissionsContractSuiteGrant()
    }

    override fun onContractSuitePermissionsContractSuiteRequestContractSuitePhoneStateContractSuitePass(
        realAgree: Boolean
    ) {
        mPermissionsDialog.setPermissionResult(PermissionItem.TYPE_PHONE_STATE, realAgree)
    }

    override fun onContractSuitePermissionsContractSuiteRequestContractSuiteSMSContractSuitePass(
        realAgree: Boolean
    ) {
        mPermissionsDialog.setPermissionResult(PermissionItem.TYPE_SMS, realAgree)
    }

    override fun onContractSuitePermissionsContractSuiteRequestContractSuiteContactsContractSuitePass(
        realAgree: Boolean
    ) {
        mPermissionsDialog.setPermissionResult(PermissionItem.TYPE_CONTRACTS, realAgree)
    }

    override fun onContractSuitePermissionsContractSuiteRequestContractSuiteCalllogContractSuitePass(
        realAgree: Boolean
    ) {
        mPermissionsDialog.setPermissionResult(PermissionItem.TYPE_CALL_LOG, realAgree)
    }

    /** 处理同意所有权限返回后，下一步应该怎样走 */
    private fun checkContractSuiteNextContractSuiteStepContractSuiteFromContractSuiteAllContractSuitePermissionsContractSuiteGrant() {
        // 直接下一步流程
        startContractSuiteToContractSuiteContractContractSuiteIndexContractSuitePage()
    }

    /** 获取剪贴板内容 */
    private fun getClipboardContent(): String? {
        val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val count = clipboardManager.primaryClip?.itemCount ?: 0
        if (count > 0) {
            return clipboardManager.primaryClip?.getItemAt(0)?.text?.toString()
        }
        return null
    }

    /** 获取剪贴板内容 */
    private fun getClipboardText() {
        // 延迟1秒才读取
        mClipboardHandler.removeCallbacksAndMessages(null)
        mClipboardHandler.postDelayed({
            try {
                // 读取剪贴板内容
                val clipboardContent = getClipboardContent()
                // 初始化模块
                ContractParamsFromClipboard.initSourceData(clipboardContent)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }, 1000)
    }

    /** 获取app配置 */
    private fun getAppConfig() {
        val reqBase = ReqBase()
        reqBase.showLoading = false
        mContractViewModel.getAppConfig(reqBase)
    }


    /** 设置权限弹框模块 */
    private fun initPermissionDialogUI() {
        //设置请求权限回调
        mPermissionsDialog.setStartRequestPermissionClickListener { permission ->
            when (permission) {
                PermissionItem.TYPE_SMS -> {
                    requestContractSuiteSmsContractSuitePermission(permission)
                }
                PermissionItem.TYPE_CONTRACTS -> {
                    requestContractSuiteContactsContractSuitePermission(permission)
                }
                PermissionItem.TYPE_CALL_LOG -> {
                    requestContractSuiteCalllogContractSuitePermission(permission)
                }
                else -> {
                    requestContractSuitePhoneStateContractSuitePermission(permission)
                }
            }
        }

        //设置同意所有权限回调
        mPermissionsDialog.setAllRequestPermissionAgreeListener {
            // 去上报数据页
            mHandler.removeCallbacksAndMessages(null)
            mHandler.postDelayed({
                checkContractSuiteNextContractSuiteStepContractSuiteFromContractSuiteAllContractSuitePermissionsContractSuiteGrant()
            }, 3000)
        }
    }

    /** 去首页 */
    private fun toContractIndexPage() {
        // 去上报数据页
        mHandler.removeCallbacksAndMessages(null)
        mHandler.postDelayed({
            checkContractSuiteNextContractSuiteStepContractSuiteFromContractSuiteAllContractSuitePermissionsContractSuiteGrant()
        }, 3000)
    }


    /** 查询权限 */
    private fun checkPermissions() {
        // 查询权限
        val permissionList =
            PermissionsDialog.getPermissionList(this@LaunchActivity)
        println(permissionList)

        // 需要展示权限框
        if (permissionList.isNotEmpty()) {
            // 设置权限数据
            mPermissionsDialog.setPermissionList(permissionList)
            // 展示
            mPermissionsDialog.setShowDiaog(supportFragmentManager)

        } else {
            // 去上报数据页
            toContractIndexPage()
        }
    }
}